package io.wdb.wxapp.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.wdb.exchange.model.RespModel;
import com.wdb.exchange.model.UserReadRecordModel;

import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.wdb.common.exception.RspCodeEnum;
import io.wdb.common.utils.R;
import io.wdb.handler.ApiServiceHandler;
import io.wdb.modules.activity.wxapp.entity.HdActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdReadActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdUserEntity;
import io.wdb.modules.activity.wxapp.entity.HdUserRankEntity;
import io.wdb.modules.activity.wxapp.service.HdActivityService;
import io.wdb.modules.activity.wxapp.service.HdReadActivityService;
import io.wdb.modules.activity.wxapp.service.HdUserService;
import io.wdb.wxapp.model.HdWxGroupReadRecordModel;
import io.wdb.wxapp.util.CommonUtil;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("/readActivity")
@Api(tags="D.readActivity api" ) 
public class HdReadActivityController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(HdReadActivityController.class);
	
	@Autowired
	private HdReadActivityService hdReadActivityService;
	
	@Autowired
	private HdUserService hdUserService;
	
	@Autowired
	private HdActivityService hdActivityService;
	
	
	@RequestMapping(value="/save", method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="保存微信群用户信息", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "encryptedData",value = "加密数据", dataType = "String", paramType = "query",required=true),
		@ApiImplicitParam(name = "iv", value = "加密算法的初始向量", dataType = "String", paramType = "query",required=true),
		@ApiImplicitParam(name = "usertoken", value = "getopenid接口返回的usertoken", dataType = "String", paramType = "query",required=true),
		@ApiImplicitParam(name = "userid", value = "getopenid接口返回userid", dataType = "String", paramType = "query",required=false),
		@ApiImplicitParam(name = "mobile", value = "getopenid接口返回moblie", dataType = "String", paramType = "query",required=false),
		@ApiImplicitParam(name = "activity_id", value = "活动ID", dataType = "String",paramType = "query", required=true)
	})
	public R save(HttpServletRequest request){
		String activity_id = request.getParameter("activity_id");
		String appid = request.getHeader("appid");
		String userid = request.getParameter("userid");
		String usertoken = request.getParameter("usertoken");
		String mobile = request.getParameter("mobile");
		logger.info("save wx group info begin ... activity_id{},usertoken{},userid{},appid{},mobile{}", activity_id, usertoken, userid, appid,mobile);
		HdUserEntity userinfo = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);

		if(isEmpty(userinfo) || isEmpty(userinfo.getSessionKey())) {//如果返回为空，表示usertoken过期
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		
		
		String sessionKey = userinfo.getSessionKey();
		String unionid = userinfo.getUnionid();
		String hduserid = userinfo.getId();
		Map<String, Object> result = new HashMap<>();
		String encryptedData = request.getParameter("encryptedData");
		String iv = request.getParameter("iv");
		
		String decryptInfo = "解密失败";
		try {
			decryptInfo = CommonUtil.decrypt(encryptedData, iv, sessionKey);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error(10001, "解密失败,"+ decryptInfo);
		}
		result.put("decryptInfo", decryptInfo);
		if(!ObjectUtils.isEmpty(decryptInfo)) {
			JSONObject jsoninfo  = JSONObject.fromObject(decryptInfo);
			if(!ObjectUtils.isEmpty(jsoninfo.get("openGId"))) {
				String groupId = jsoninfo.getString("openGId");
				
				//保存微信群 用户信息
				HdReadActivityEntity readActivityEntity = new HdReadActivityEntity();
				readActivityEntity.setWxGroupId(groupId);
				readActivityEntity.setWxGroupName("groupName");
				readActivityEntity.setCreateTime(new Date());
				readActivityEntity.setActivityId(activity_id);
				readActivityEntity.setUnionid(unionid);
				readActivityEntity.setUserId(hduserid);
				logger.info("saveShareInfo---readActivityEntity 's request: [{}]", JSON.toJSONString(readActivityEntity));
				hdReadActivityService.save(readActivityEntity);
			}
		}
		logger.info("save wx group info end params:{}",result);
		return R.ok(result);
	}

	 public static Map<String, Object> json2map(String str_json) {
	        Map<String, Object> res = null;
	        try {
	            Gson gson = new Gson();
	            res = gson.fromJson(str_json, new TypeToken<Map<String, Object>>() {
	            }.getType());
	        } catch (JsonSyntaxException e) {
	        	e.printStackTrace();
	        }
	        return res;
	  }
	
	@RequestMapping(value="/queryPersonInWeekRankActivity", method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="群排行个人数据,同时返回群内所有人员数据在items中", notes="依赖解密后的openGId")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "groupId",value = "加密数据", dataType = "String", paramType = "query",required=true),
		@ApiImplicitParam(name = "activity_id", value = "活动ID", dataType = "String",paramType = "query", required=true),
		@ApiImplicitParam(name = "usertoken",value = "usertoken", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "userid", value = "用户id", dataType = "String",paramType = "query", required=false),
		@ApiImplicitParam(name = "mobile", value = "mobile", dataType = "String",paramType = "query", required=false)

	})
	public Map queryPersonInWeekRankActivity(HttpServletRequest request) {
		//根据userid实时查询排名信息
		//返回当前用户群信息
		//判断是否有userinfo信息
		String userid = request.getParameter("userid");
		String groupId = request.getParameter("groupId");
		String usertoken = request.getParameter("usertoken");
		String mobile = request.getParameter("mobile");
		String appid = request.getHeader("appid");
		
		logger.info("queryPersonInWeekRankActivity request pramas:userid{},usertoken:{},groupId{},appid{}", userid, usertoken, groupId, appid);
		
		checkIsNull(groupId, "groupId");
		checkIsNull(usertoken, "usertoken");
		checkIsNull(appid,"appid");
		
		HdUserEntity userinfoApi = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);

		if(isEmpty(userinfoApi) || isEmpty(userinfoApi.getSessionKey())) {//如果返回为空，表示usertoken过期
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}

		
		if(isEmpty(userid)) {
			userid = userinfoApi.getUserid();
		}
		String unionid = userinfoApi.getUnionid();
		String userName = userinfoApi.getNickname();
		String imgurl = userinfoApi.getAvatar();
		
		HdUserEntity hdUser = new HdUserEntity();
		HdWxGroupReadRecordModel model = new HdWxGroupReadRecordModel();//返回的个人信息

		int total_record = 0;
		int week_record = 0;
		int month_record = 0;
		if(!isEmpty(userid)) {
			
			RespModel respModel = apiServiceHandler.userReadRecord(Long.valueOf(userid));
			if(respModel != null && respModel.getCode() == 0 && 
					!CommonUtil.isEmpty(respModel.getDetails())) {
				UserReadRecordModel userReadRecord = (UserReadRecordModel) respModel.getDetails().get("userReadRecord");
				total_record = userReadRecord.getTotalRead();
				week_record = userReadRecord.getWeekRecord();
				month_record = userReadRecord.getMonthRecord();
			}
			model.setBook_count(week_record);
			//更新数据
			hdUser.setUnionid(unionid);
			hdUser.setMonthRead(month_record);
			hdUser.setWeekRead(week_record);
			hdUser.setTotalRead(total_record);
			hdUserService.updateByUnionid(hdUser);
		}
		int rank = 1;
		String rank_percentage = "100%";
		String cumulative_time = "0";
		
		//查询群内union信息
		Map<String, Object> readActityQuery = new HashMap<>();
		readActityQuery.put("wxGroupId", groupId);
		List<HdReadActivityEntity> entities =  hdReadActivityService.queryList(readActityQuery);
		
		List<HdUserRankEntity> rankInfo = null;
		if(!ObjectUtils.isEmpty(entities)) {
			//TODO查询群内用户的所有借阅记录
			Map<String, Object> unionidMap = new HashMap<>();
			List<String> unionids = new ArrayList<>();
			for(HdReadActivityEntity entity:entities) {
				unionids.add(entity.getUnionid());
			}
			unionidMap.put("unionid", unionids);
			rankInfo = hdUserService.queryWeekReadingList(unionidMap);
		}
		//查询排名
		if(!ObjectUtils.isEmpty(rankInfo)) {
			for(HdUserRankEntity readRank: rankInfo) {
				if(unionid.equals(readRank.getUnionid())) {
					rank = readRank.getRank();
				}
			}
			//打败了本群用户的百分比
			rank_percentage = rank* 100/new Double(rankInfo.size())  +"%";
		}
		model.setRank(rank);
		model.setRank_percentage(rank_percentage);
		model.setCumulative_time(cumulative_time);
		model.setImgurl(imgurl);
		model.setUser_name(userName);
		
		List<HdWxGroupReadRecordModel> models = HdWxGroupReadRecordModel.convert(rankInfo);
		logger.info("queryPersonInWeekRankActivity respones data detail:{},items:{}",JSON.toJSONString(model),JSON.toJSONString(models));
		HdActivityEntity hdActivity= hdActivityService.queryObject(request.getParameter("activity_id"));
		return R.ok().put("detail", model).put("items", models).put("content", hdActivity.getContent());
	}
}
